/*
 * Copyright 2021 The happyProxy Project
 *
 * The happyProxy Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.sinosoft.lingkang.happyproxy.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

/**
 * @Author 绫小路
 * @Date 2021/2/22
 */
public class RemoteServerResponseHandler extends ChannelInboundHandlerAdapter {

  private static final InternalLogger logger = InternalLoggerFactory.getInstance(RemoteServerResponseHandler.class);
  private final Channel inChannel;

  private HttpProxyServerFlowCount httpProxyServerFlowCount;

  public RemoteServerResponseHandler(Channel inChannel, HttpProxyServerFlowCount httpProxyServerFlowCount) {
    this.inChannel = inChannel;
    this.httpProxyServerFlowCount = httpProxyServerFlowCount;
  }


  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    ctx.read();
  }

  @Override
  public void channelRead(final ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;
    //流量统计
    if (httpProxyServerFlowCount != null) {
      httpProxyServerFlowCount.downLoadByte(byteBuf.readableBytes());
    }
    inChannel.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
      public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (channelFuture.isSuccess()) {
          ctx.channel().read();
        } else {
          channelFuture.channel().close();
        }
      }
    });
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    closeOnFlush(inChannel);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    logger.error(cause);
    closeOnFlush(ctx.channel());
  }

  private void closeOnFlush(Channel ch) {
    if (ch.isActive()) {
      ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
  }
}
